package com.waa.gulimall.product.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waa.gulimall.common.constant.ProductConstant;
import com.waa.gulimall.common.utils.PageUtils;
import com.waa.gulimall.common.utils.Query;
import com.waa.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.waa.gulimall.product.dao.AttrDao;
import com.waa.gulimall.product.dao.AttrGroupDao;
import com.waa.gulimall.product.dao.CategoryDao;
import com.waa.gulimall.product.entity.*;

import com.waa.gulimall.product.service.AttrService;
import com.waa.gulimall.product.service.CategoryService;
import com.waa.gulimall.product.vo.AttrGroupRelationVo;
import com.waa.gulimall.product.vo.AttrRespVo;
import com.waa.gulimall.product.vo.AttrVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
@Slf4j
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrDao attrDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
//        attrEntity.setAttrName(attr.getAttrName());
        BeanUtils.copyProperties(attr, attrEntity);
        //1、保存基本数据
        this.save(attrEntity);
        //2、保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            log.info("保存关联关系");
            final AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        final QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        attrEntityQueryWrapper.eq("attr_type", "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE
                .getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        log.info("catelogId" + catelogId + "");
        if (catelogId != 0) {
            attrEntityQueryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            attrEntityQueryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityQueryWrapper);

        final List<AttrEntity> records = page.getRecords();
        for (AttrEntity record : records) {
            log.info("records:" + record.getAttrId());
        }

        final List<AttrRespVo> attrRespVoList = records.stream().map((attrEntity) -> {
            final AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //设置分类和分组名称
            if ("base".equalsIgnoreCase(type)) {
                try {
                    final AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                    final Long attrGroupId = relationEntity.getAttrGroupId();
                    if (attrGroupId != null) {
                        final AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                } catch (NullPointerException e) {
                    System.out.println(e.toString());
                }
            }

            final CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            attrRespVo.setCatelogName(categoryEntity.getName());
            return attrRespVo;
        }).collect(Collectors.toList());
        final PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }


    //查询要修改的规格参数内容
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        final AttrEntity attrEntity = this.getById(attrId);
        final AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        //设置分组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            final AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                final Long attrGroupId = relationEntity.getAttrGroupId();
                if (attrGroupId != null) {
                    attrRespVo.setAttrGroupId(attrGroupId);
                    final AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    if (attrGroupEntity != null)
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //设置分类信息
        final Long catelogId = attrEntity.getCatelogId();
        final CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        final Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        return attrRespVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        final AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        //修改分组关联
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            final Long count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            final AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            if (count > 0) {
                relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                relationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        return null;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {

    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //查出所属分类
        final Long catelogId = attrGroupDao.selectById(attrgroupId).getCatelogId();
        //当前分组只能关联自己所属分类里面的所有属性
        final List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().ne("attr_group_id", 0));
        final List<Long> collect = attrgroupRelationEntityList.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        final QueryWrapper<AttrEntity> wapper = new QueryWrapper<AttrEntity>().notIn("attr_id", collect).and(item -> {
            item.eq("catelog_id", catelogId);
        });
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            wapper.and(w -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        final IPage<AttrEntity> attrEntityIPage = this.page(new Query<AttrEntity>().getPage(params), wapper.and((w) -> {
            w.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        }));
        return new PageUtils(attrEntityIPage);
    }


    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {
        final List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        if (!relationEntities.isEmpty()) {
            final List<Long> listid = relationEntities.stream().map((entity) -> {
                return entity.getAttrId();
            }).collect(Collectors.toList());
            final List<AttrEntity> attrEntities = this.listByIds(listid);
            return attrEntities;
        }
        return null;
    }


}